package com.gsp.framework.helper;

import com.gsp.framework.util.PropsUtil;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

public class DatabaseHelper {
    private static final Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
    private static final QueryRunner QUERY_RUNNER;
    private static final ThreadLocal<Connection> CONNECTION_HOLDER;
    private static final BasicDataSource DATA_SOURCE;

    static {
        QUERY_RUNNER = new QueryRunner();
        CONNECTION_HOLDER = new ThreadLocal<>();
        Properties prop = PropsUtil.loadProps("conf/mybatis/jdbc.properties");
        String driver = prop.getProperty("jdbc_driverClassName");
        String url = prop.getProperty("jdbc_url");
        String username = prop.getProperty("jdbc_username");
        String password = prop.getProperty("jdbc_password");
        DATA_SOURCE = new BasicDataSource();
        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setUsername(username);
        DATA_SOURCE.setPassword(password);
    }

    public static Connection getConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn == null) {
            try {
                conn = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                log.error("get connection failure", e);
            } finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
        return conn;
    }


    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> resultList = null;
        try {
            Connection conn = getConnection();
            resultList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<>(entityClass), params);
        } catch (SQLException e) {
            log.error("query entity list error", e);
        }
        return resultList;
    }

    public static <T> T queryEntity(Class<T> entityClass, String sql, Object... params) {
        T result = null;
        try {
            Connection conn = getConnection();
            result = QUERY_RUNNER.query(conn, sql, new BeanHandler<>(entityClass), params);
        } catch (SQLException e) {
            log.error("query entity error", e);
        }
        return result;
    }

    public static <T> boolean insertEntity(Class<T> classEntity, Map<String, Object> param) {
        if (param == null || param.isEmpty()) {
            log.error("can not insert entity : param is empty");
            return false;
        }
        StringBuilder sql = new StringBuilder("insert into ");
        StringBuilder values = new StringBuilder("(");
        sql.append(classEntity.getSimpleName().toLowerCase()).append("(");
        for (String key : param.keySet()) {
            sql.append(key + ",");
        }
        sql.replace(sql.lastIndexOf(","), sql.length(), ")");
        sql.append(" values (");
        for (int i = 0; i < param.size(); i++) {
            sql.append("?,");
        }
        sql.replace(sql.lastIndexOf(","), sql.length(), ")");
        return excuteUpdate(sql.toString(), param.values().toArray()) == 1;
    }

    public static <T> boolean updateEntity(Class<T> classEntity, long id, Map<String, Object> param) {
        if (param == null || param.isEmpty()) {
            log.error("can not update entity : param is empty");
            return false;
        }
        StringBuilder sql = new StringBuilder("update ");
        sql.append(classEntity.getSimpleName().toLowerCase()).append(" set ");
        for (String key : param.keySet()) {
            sql.append(key + "=?,");
        }
        sql.replace(sql.lastIndexOf(","), sql.length(), " ");
        sql.append("where id = ?");
        List<Object> paramList = new ArrayList<>();
        paramList.addAll(param.values());
        paramList.add(id);
        return excuteUpdate(sql.toString(), paramList.toArray()) == 1;
    }

    public static <T> boolean deleteEntity(Class<T> classEntity, long id) {
        StringBuilder sql = new StringBuilder("delete from ");
        sql.append(classEntity.getSimpleName().toLowerCase()).append(" where id = ?");
        return excuteUpdate(sql.toString(), id) == 1;
    }

    public static <T> List<T> getEntityList(Class<T> classEntity) {
        StringBuilder sql = new StringBuilder("select *  from ");
        sql.append(classEntity.getSimpleName().toLowerCase());
        return queryEntityList(classEntity, sql.toString());
    }

    public static <T> T getEntity(Class<T> classEntity, long id) {
        StringBuilder sql = new StringBuilder("select *  from ");
        sql.append(classEntity.getSimpleName().toLowerCase()).append(" where id = ?");
        return queryEntity(classEntity, sql.toString(), id);
    }


    public static List<Map<String, Object>> excuteQuery(String sql, Object... params) {
        List<Map<String, Object>> result = null;
        try {
            Connection conn = getConnection();
            result = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
        } catch (SQLException e) {
            log.error("query entity error", e);
        }
        return result;
    }

    public static int excuteUpdate(String sql, Object... params) {
        int result = 0;
        try {
            Connection conn = getConnection();
            result = QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            log.error("query entity error", e);
        }
        return result;
    }

    public static void executeSqlFile(String filePath) {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String sql;
        try {
            while ((sql = br.readLine()) != null) {
                excuteUpdate(sql);
            }
        } catch (IOException e) {
            log.error("executeSqlFile error", e);
        }
    }


}
